package com.ken.blog.controller.web;

import com.ken.blog.component.CategoryComponent;
import com.ken.blog.domain.Article;
import com.ken.blog.domain.Category;
import com.ken.blog.domain.ArticleRepository;
import com.ken.blog.domain.CategoryRepository;
import com.ken.blog.tools.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private ArticleRepository articleRepository;

    @RequestMapping("")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView("web/category/index");
        return mv;
    }

    @RequestMapping("/{id}")
    @ResponseBody
    public ModelAndView info(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id, String page) {
        ModelAndView mv = new ModelAndView("web/category/index");

        Category category = categoryRepository.findOne(id);

        //处理分页请求
        int pageSize = Pagination.getPageSize(page);

        Pageable pageable = new PageRequest(pageSize, 2);
        Page<Article> pageList = articleRepository.findByCategory(category, pageable);

        List<Article> list = pageList.getContent();

        //分页功能
        Map pagination = Pagination.simgle(pageList.getTotalPages(), pageSize + 1);

        mv.addObject("pagination", pagination);
        mv.addObject("list", list);
        mv.addObject("categoryId", id);

        return mv;
    }
}